<?php
include_once dirname(dirname(__FILE__)).'/nn_db.class.php';

class sp_model
{
	static public function get_sp_list($sp_id=null)
    {
		$db = nn_get_db(NL_DB_READ);		
		$sql  = "select * from nns_mgtvbk_sp";
		if($sp_id!=null)
		{
			$sql  = "select * from nns_mgtvbk_sp where nns_id='".$sp_id."'";
		}	
		return nl_db_get_all($sql,$db);
	}

	static public function get_sp_info($sp_id)
    {
		$db = nn_get_db(NL_DB_READ);
		$sql ="select * from nns_mgtvbk_sp where nns_id='".$sp_id."'";
		return nl_db_get_one($sql,$db);
	}

	static public function exists_sp($id)
    {
		$db = nn_get_db(NL_DB_READ);	
		$sql = "select 1 from nns_mgtvbk_sp where nns_id='".$id."'";
		$result = nl_db_get_all($sql,$db);
		if(is_array($result) && count($result) > 0)
		{
			return true;
		}
		else
        {
			return false;
		}
	}

	static public function add_sp($sp_info)
    {
        global $g_bk_version_number;
        $bk_version_number = $g_bk_version_number == '1' ? true : false;
        unset($g_bk_version_number);

		$db = nn_get_db(NL_DB_WRITE);
		$sp_info['nns_create_time'] = date('Y-m-d H:i:s');
		//$sp_info['nns_rule'] = isset($sp_info['nns_rule']) ? implode(',',$sp_info['nns_rule']): null;
		
		$sp_info_nns_config = json_decode($sp_info['nns_config'],true);
		if(!$bk_version_number)
        {
            $file = '<?php'.PHP_EOL;
            $file .= 'define("C2_FTP","'.$sp_info_nns_config['xml_ftp'].'");'.PHP_EOL;
            $file .= 'define("MOVIE_FTP","'.$sp_info_nns_config['media_ftp'].'");'.PHP_EOL;
            $file .= 'define("HW_DOANLOAD_IMG_FTP","'.$sp_info_nns_config['img_ftp'].'");'.PHP_EOL;
            $file .= 'define("MGTV_MEDIA_DOWNLOAD_URL","'.$sp_info_nns_config['down_url'].'");'.PHP_EOL;
            $file .= 'define("IMPROT_EPG_URL","'.$sp_info_nns_config['epg_url'].'");'.PHP_EOL;
            $file .= 'define("IMPROT_EPG_ONLINE_URL","'.$sp_info_nns_config['online_api'].'");'.PHP_EOL;
            //$file .= 'define("IMPROT_EPG_LOG","'.$sp_info_nns_config['epg_log'].'");'.PHP_EOL;
            $file .= 'define("HW_DOANLOAD_IMG_METHOD","ftp");'.PHP_EOL;
            $file .= 'define("DRM_KEY_URL","'.$sp_info_nns_config['q_drm_key_file_url'].'");'.PHP_EOL;
            $file .= 'define("IMPROT_EPG_LOG",dirname(dirname(dirname(__FILE__)))."/data/log/import/'.$sp_info['nns_id'].'");'.PHP_EOL;
            $file .= 'define("MEDIA_TIME_OUT","300");'.PHP_EOL;
            $file .= 'define("CSP_ID","'.$sp_info_nns_config['import_csp_id'].'");'.PHP_EOL;

            $filename = 'define.php';
            $file_path = dirname(dirname(__FILE__)).'/'.$sp_info['nns_id'].'/';
            if(!is_dir($file_path)) mkdir($file_path,0777,true);
            $file_path .= $filename;
            if (!file_exists($file_path))
            {
                file_put_contents($file_path,$file);
            }


            $drm_file = '<?php'.PHP_EOL;
            $drm_file .= '$g_drm_enable = 1;'.PHP_EOL;
            $drm_file .= '$g_drm_vendor = array("vcas"=>1,);'.PHP_EOL;
            $drm_file .= '$g_drm_vcas_admin_manager_service_url = "https://192.168.90.69:8090/services/AdminMgmtService?wsdl";'.PHP_EOL;
            $drm_file .= '$g_drm_vcas_content_manager_service_url = "https://192.168.90.69:8090/services/ContentMgmtService?wsdl";'.PHP_EOL;
            $drm_file .= '$g_drm_vcas_network_id = "test_network_id";'.PHP_EOL;
            $drm_file .= '$g_drm_vcas_network_type = "OTT";'.PHP_EOL;
            $drm_file .= '$g_drm_vcas_manager_user_name = "admin";'.PHP_EOL;
            $drm_file .= '$g_drm_vcas_manager_password = "starcor";'.PHP_EOL;

            $drm_filename = 'drm_config.php';
            $file_path = dirname(dirname(__FILE__)).'/'.$sp_info['nns_id'].'/';
            if(!is_dir($file_path)) mkdir($file_path,0777,true);
            $file_path .= $drm_filename;
            if (!file_exists($file_path))
            {
                file_put_contents($file_path,$drm_file);
            }


            $ini_file = '<?php'.PHP_EOL;
            $ini_file .='include_once dirname(__FILE__).\'/define.php\';'.PHP_EOL;
            //加载DRM配置文件
            $ini_file .='include_once dirname(__FILE__).\'/drm_config.php\';'.PHP_EOL;
            //加载DRM片源处理文件
            $ini_file .='include_once dirname(dirname(__FILE__)).\'/models/drm/manager/media.class.php\';'.PHP_EOL;
            $ini_file .='function '.$sp_info['nns_id'].'_model_autoload($classname){'.PHP_EOL;
            $ini_file .='$file = dirname(__FILE__)."/models/".$classname.".php";'.PHP_EOL;
            $ini_file .='if(file_exists($file)){'.PHP_EOL;
            $ini_file .='include_once $file;'.PHP_EOL;
            $ini_file .='return true;'.PHP_EOL;
            $ini_file .='}'.PHP_EOL;
            $ini_file .='return false;'.PHP_EOL;
            $ini_file .='}'.PHP_EOL;
            $ini_file .='spl_autoload_register("'.$sp_info['nns_id'].'_model_autoload");'.PHP_EOL;
            //生成读取DRM配置文件方法
            $ini_file .= 'function get_drm_config($drm_config){' . PHP_EOL;
            $ini_file .= 'global $$drm_config;' . PHP_EOL;
            $ini_file .= 'return $$drm_config;' . PHP_EOL;
            $ini_file .='}'.PHP_EOL;

            $filename_init = 'init.php';
            $file_path_init = dirname(dirname(__FILE__)).'/'.$sp_info['nns_id'].'/';
            if(!is_dir($file_path_init)) mkdir($file_path_init,0777,true);
            $file_path_init .= $filename_init;
            if (!file_exists($file_path_init))
            {
                file_put_contents($file_path_init,$ini_file);
            }
        }

        global $g_project_name;
        $p_name = $g_project_name;
        unset($g_project_name);
		if ($bk_version_number)
        {
            $file_path_v2_sp = dirname(dirname(dirname(__FILE__))).'/v2/ns_api/' . $p_name . '/delivery/' .$sp_info['nns_id'].'/';
            if(!is_dir($file_path_v2_sp)) mkdir($file_path_v2_sp,0777,true);

            //delivery文件的生成
            if ($sp_info['nns_config']['disabled_cdn'] != 1)
            {
                $delivery_file = '<?php'.PHP_EOL;
                //加载公共文件
                $delivery_file .='include_once dirname(dirname(dirname(dirname(dirname(__FILE__)))))."/common.php";'.PHP_EOL;
                $delivery_file .='\ns_core\m_load::load("ns_model.delivery.cdn_delivery_explain");'.PHP_EOL;

                $delivery_file .='class delivery extends \ns_model\delivery\cdn_delivery_explain {'.PHP_EOL;
                $delivery_file .='public function explain(){'.PHP_EOL;
                $delivery_file .='}'.PHP_EOL;
                $delivery_file .='}'.PHP_EOL;
                $delivery_file_name = 'delivery.class.php';
                //生成delivery文件
                $delivery_file_path = $file_path_v2_sp . $delivery_file_name;
                if (!file_exists($delivery_file_path))
                {
                    file_put_contents($delivery_file_path,$delivery_file);
                }

                //notify供cdn异步反馈的接收文件
                $notify_file = '<?php'.PHP_EOL;
                //加载公共文件
                $notify_file .='include_once dirname(dirname(dirname(dirname(dirname(__FILE__)))))."/common.php";'.PHP_EOL;

                $notify_file .='class notify {'.PHP_EOL;
                $notify_file .='public function __construct(){'.PHP_EOL;
                $notify_file .='}'.PHP_EOL;
                $notify_file .='}'.PHP_EOL;
                $notify_file_name = 'notify.php';
                //生成delivery文件
                $notify_file_path = $file_path_v2_sp . $notify_file_name;
                if (!file_exists($notify_file_path))
                {
                    file_put_contents($notify_file_path,$notify_file);
                }
            }
        }

		return nl_db_insert($db,'nns_mgtvbk_sp',$sp_info);
	}

	static public function update_sp($sp_info)
    {
        global $g_bk_version_number;
        $bk_version_number = $g_bk_version_number == '1' ? true : false;
        unset($g_bk_version_number);

		$db = nn_get_db(NL_DB_WRITE);
		$set = array(
            'nns_name'=>$sp_info['nns_name'],
            'nns_modify_time'=>date('Y-m-d H:i:s'),
            'nns_telphone' =>  $sp_info['nns_telphone'],
            'nns_email' =>  $sp_info['nns_email'],
            'nns_contact' =>  $sp_info['nns_contact'],
            'nns_config' =>  $sp_info['nns_config'],
            //'nns_rule' =>  isset($sp_info['nns_rule'] ) ? implode(',',$sp_info['nns_rule']) : null,
		);
		$where = "nns_id='".$sp_info['nns_id']."'";
		
		
		
		$sp_info_nns_config = json_decode($sp_info['nns_config'],true);
		
		//print_r($sp_info['nns_config']);
        if(!$bk_version_number)
        {
            $file = '<?php'.PHP_EOL;
            $file .= 'define("C2_FTP","'.$sp_info_nns_config['xml_ftp'].'");'.PHP_EOL;
            $file .= 'define("MOVIE_FTP","'.$sp_info_nns_config['media_ftp'].'");'.PHP_EOL;
            $file .= 'define("HW_DOANLOAD_IMG_FTP","'.$sp_info_nns_config['img_ftp'].'");'.PHP_EOL;
            $file .= 'define("MGTV_MEDIA_DOWNLOAD_URL","'.$sp_info_nns_config['down_url'].'");'.PHP_EOL;
            $file .= 'define("IMPROT_EPG_URL","'.$sp_info_nns_config['epg_url'].'");'.PHP_EOL;
            $file .= 'define("IMPROT_EPG_ONLINE_URL","'.$sp_info_nns_config['online_api'].'");'.PHP_EOL;
            //$file .= 'define("IMPROT_EPG_LOG","'.$sp_info_nns_config['epg_log'].'");'.PHP_EOL;
            $file .= 'define("HW_DOANLOAD_IMG_METHOD","ftp");'.PHP_EOL;
            $file .= 'define("DRM_KEY_URL","'.$sp_info_nns_config['q_drm_key_file_url'].'");'.PHP_EOL;
            $file .= 'define("IMPROT_EPG_LOG",dirname(dirname(dirname(__FILE__)))."/data/log/import/'.$sp_info['nns_id'].'");'.PHP_EOL;
            $file .= 'define("MEDIA_TIME_OUT","300");'.PHP_EOL;
            $file .= 'define("CSP_ID","'.$sp_info_nns_config['import_csp_id'].'");'.PHP_EOL;
            if (!empty($sp_info_nns_config['cdn_send_mode_url']))
            {
                $file .= 'define("CDN_SEND_MODE_HTTP_URL","'.$sp_info_nns_config['cdn_send_mode_url'].'");'.PHP_EOL;
            }

            $filename = 'define.php';
            $file_path = dirname(dirname(__FILE__)).'/'.$sp_info['nns_id'].'/';
            if(!is_dir($file_path)) mkdir($file_path,0777,true);
            $file_path .= $filename;
            file_put_contents($file_path,$file);
            $ini_file = '<?php'.PHP_EOL;
            $ini_file .='include_once dirname(__FILE__).\'/define.php\';'.PHP_EOL;
            //加载DRM配置文件
            $ini_file .='include_once dirname(__FILE__).\'/drm_config.php\';'.PHP_EOL;
            //加载DRM片源处理文件
            $ini_file .='include_once dirname(dirname(__FILE__)).\'/models/drm/manager/media.class.php\';'.PHP_EOL;
            $ini_file .='function '.$sp_info['nns_id'].'_model_autoload($classname){'.PHP_EOL;
            //$ini_file .='$file = dirname(dirname(__FILE__))."/common/models/".$classname.".php";'.PHP_EOL;
            $ini_file .='$file = dirname(__FILE__)."/models/".$classname.".php";'.PHP_EOL;
            $ini_file .='if(file_exists($file)){'.PHP_EOL;
            $ini_file .='include_once $file;'.PHP_EOL;
            $ini_file .='return true;'.PHP_EOL;
            $ini_file .='}'.PHP_EOL;
            $ini_file .='return false;'.PHP_EOL;
            $ini_file .='}'.PHP_EOL;
            $ini_file .='spl_autoload_register("'.$sp_info['nns_id'].'_model_autoload");'.PHP_EOL;
            //生成读取DRM配置文件方法
            $ini_file .= 'function get_drm_config($drm_config){' . PHP_EOL;
            $ini_file .= 'global $$drm_config;' . PHP_EOL;
            $ini_file .= 'return $$drm_config;' . PHP_EOL;
            $ini_file .='}'.PHP_EOL;

            $filename_init = 'init.php';
            $file_path_init = dirname(dirname(__FILE__)).'/'.$sp_info['nns_id'].'/';
            if(!is_dir($file_path_init)) mkdir($file_path_init,0777,true);
            $file_path_init .= $filename_init;
            file_put_contents($file_path_init,$ini_file);
        }

		
		return nl_db_update($db,'nns_mgtvbk_sp',$set,$where);
	}
	static public function delete_sp($sp_id)
    {
		$db = nn_get_db(NL_DB_WRITE);

		$sql = "delete from nns_sp where nns_id='".$sp_id."'";
	    return nl_execute_by_db($sql,$db);
	}

	static public function batch_delete_sp($sp_ids)
    {
		$db = nn_get_db(NL_DB_WRITE);
	
		$sql = "delete from nns_mgtvbk_sp where ".nl_db_in($sp_ids,'nns_id');
		return nl_execute_by_db($sql,$db);
	}	
	//获取SP的配置文件	
	/**
	 * sp_id
	 * action
	 */
	static public function get_sp_config($sp_id,$action=null)
    {
		$sp_info = self::get_sp_info($sp_id);
		$nns_config = array();
		if(!empty($sp_info['nns_config']))
		{
			$nns_config = json_decode($sp_info['nns_config'],true);
		}	
		if($action===null)
		{
			$arr_bind_cp_list = null;
			if(isset($sp_info['nns_bind_cp']) && strlen($sp_info['nns_bind_cp']) > 0)
			{
				$arr_bind_cp_list = explode(',', $sp_info['nns_bind_cp']);
				if(is_array($arr_bind_cp_list) && !empty($arr_bind_cp_list))
				{
					foreach ($arr_bind_cp_list as $key=>$val)
					{
						if(strlen($val) < 1)
						{
							unset($arr_bind_cp_list[$key]);
						}
					}
					$arr_bind_cp_list = (!empty($arr_bind_cp_list) && is_array($arr_bind_cp_list)) ? array_values($arr_bind_cp_list) : null;
				}
			}
			$nns_config['temp_bind_cp_list'] = $arr_bind_cp_list;
			return $nns_config;
		}
		if(isset($nns_config[$action])&&!empty($nns_config[$action]))
		{
			$re = $nns_config[$action];
			foreach ($re as $key => $value)
			{
				$re[$key] = (int) $value;
			}
			return $re;
		}
		else
        {
			return array('status'=>0,'priority'=>0,'audit'=>0);
		}
	}

}
